import 'dart:async';

import 'package:agora_rtc_engine/rtc_engine.dart';
import 'package:flutter/material.dart';
import 'package:agora_rtc_engine/rtc_remote_view.dart' as RtcRemoteView;
import 'package:flutter_application_cyber/pages/Mine/cn_coinStore_Page.dart';
import 'package:provider/provider.dart';
import '../../model/cn_net_response.dart';

import 'package:flutter_application_cyber/net/cn_net_helper.dart';

import 'package:flutter_application_cyber/model/cn_user_default_cache.dart';
import 'cn_mine_video_view.dart';
import 'cn_bottom_keyboard.dart';
import 'cn_message_item_view.dart';
import 'package:flutter_application_cyber/tools/cn_app_popView.dart';
import 'cn_gift_animation_view.dart';
import 'package:flutter_application_cyber/pages/Mate/Models/cn_channel_model.dart';
import 'package:permission_handler/permission_handler.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:flutter_util_code/toast_utils.dart';
import 'package:flutter_application_cyber/pages/Mate/Models/cn_AnchorViewModel.dart';
import '../../tools/cn_event_bus.dart';
import 'package:flutter_application_cyber/tools/cn_event_busUtils.dart';

class CnCallingPage extends StatefulWidget {
  final String userId;
  final UserInfoModel? userData;
  final CnChannelModel _CnChannelModel;

  const CnCallingPage(this._CnChannelModel,
      {required this.userData, required this.userId, super.key});

  @override
  State<StatefulWidget> createState() => CallingState();
}

class CallingState extends State<CnCallingPage> with TickerProviderStateMixin {
  int uid = 1;
  RtcEngine? _rtcEngine; //声网对象
  late RtcEngineEventHandler _eventHandler; //声网事件处理
  bool isRear = false;
  UserInfoModel? _userInfo;
  final TextEditingController _editingController = TextEditingController();
  final ScrollController _scrollController = ScrollController();
  var imList = <Widget>[];
  int availableCoins = 0;
  String giftName = ""; //礼物名
  late AnimationController _controller;
  late AnimationController _scaleController;
  Timer? _giftTimer;
  bool isFollow = false; //是否已经关注
  FocusScopeNode focusScopeNode = FocusScopeNode();
  Timer? endTime;

  Future<RtcEngine> getRtcEngine() async {
    var rtcKey = await CnUserDefaultCacheHelper.getUserDefault(kAgoraRtcAppKey);
    return await RtcEngine.create(rtcKey);
  }

  UserInfoModel getMineInfo() {
    return Provider.of<ChangeUserInfoModel>(context, listen: false).info;
  }

  void hideKeyboard() {
    focusScopeNode.unfocus();
  }

  @override
  void dispose() {
    // TODO: implement dispose
    super.dispose();
    EventBusUtils.getInstance()?.fire(EventKeys.applePaySuccess);

    _rtcEngine?.leaveChannel();
    _rtcEngine?.destroy();
    _editingController.dispose();
    _scrollController.dispose();
    _scaleController.dispose();
    _controller.dispose();
    _giftTimer?.cancel();
    endTime?.cancel();
  }

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    getPermission();
    setState(() {
      _userInfo = widget.userData;
    });

    /// 初始化动画控制器
    _controller = AnimationController(
      duration: const Duration(milliseconds: 1500),
      vsync: this,
    );

    _scaleController = AnimationController(
      duration: const Duration(milliseconds: 1500),
      vsync: this,
    );

    ///动画监听
    _controller.addStatusListener((status) {
      if (status == AnimationStatus.completed) {
        _scaleController.forward();
      }
    });

    _scaleController.addStatusListener((status) {
      if (status == AnimationStatus.completed) {
        _controller.reverse();
      }
    });

    getCoins();

//     //声网事件处理
    _eventHandler = RtcEngineEventHandler(
        userJoined: (int uid, int elapsed) {
          setState(() {
            this.uid = uid;
          });
        },
        joinChannelSuccess: (String channel, int uid, int elapsed) {
          joinChannel(channel, uid); //调用加入频道接口
        },
        error: (err) {
          EasyLoading.dismiss();
          _hangUp();
        },
        userOffline: (int uid, UserOfflineReason reason) {});

    //声网对象设置
    creatRtcEngine();
  }

  creatRtcEngine() async {
    var rtcKey = await CnUserDefaultCacheHelper.getUserDefault(kAgoraRtcAppKey);
    _rtcEngine = await RtcEngine.create(rtcKey);
    _rtcEngine?.setEventHandler(_eventHandler);
    await _rtcEngine?.enableVideo();
    await _rtcEngine?.setDefaultAudioRouteToSpeakerphone(true);
    await _rtcEngine?.adjustPlaybackSignalVolume(150);
    await _rtcEngine?.enableDualStreamMode(true);
    await _rtcEngine
        ?.setLocalPublishFallbackOption(StreamFallbackOptions.VideoStreamLow);
//       请求麦克风权限，如果没有权限就会设置 mute掉本地视频流
// 请求麦克风权限，如果没有权限就会设置 mute掉本地视频流
    PermissionStatus statuses2 = await Permission.microphone.status;
    if (statuses2 != PermissionStatus.granted) {
      _rtcEngine?.enableLocalAudio(false);
    } else {
      _rtcEngine?.enableLocalAudio(true);
    }
    await _rtcEngine?.joinChannelWithUserAccount(
        widget._CnChannelModel.rtcToken,
        widget._CnChannelModel.channelName,
        getMineInfo().userId ?? "0");
  }

  _startGiftTimer() {
    if (_giftTimer != null) {
      _giftTimer?.cancel();
      _giftTimer = null;
    }
    _giftTimer ??= Timer(const Duration(seconds: 5), () {
      if (mounted) {
        setState(() {
          giftName = "";
        });
      }
    });
  }

  _startAnimation() {
    _controller.reset();
    _scaleController.reset();
    _controller.forward();
  }

  //加入频道接口
  void joinChannel(String channelName, int channelUid) async {
    HDHResponseData? response = await CnNetHelper.join(channelName, '$uid');
    if (response != null) {
      setState(() {
        uid = uid;
      });
      EasyLoading.dismiss();
      endTime = Timer(const Duration(seconds: 10), () {
        _hangUp();
      });
    }
  }

  void _hangUp() {
    // if (!ClickUtils.isClick()) return;

    CnNetHelper.hangUpCall(widget._CnChannelModel.channelName, (bool data) {
      final routeToRemove = ModalRoute.of(context);
      Navigator.of(context).removeRoute(routeToRemove!);
    });
  }

  //字符串截取
  String getSubString({required int end, required String str}) {
    if (str.length > end) {
      return "${str.substring(0, end)}...";
    } else {
      return str;
    }
  }

  //列表滚动
  void scrollList() async {
    await Future.delayed(const Duration(milliseconds: 200));
    _scrollController.animateTo(
      _scrollController.position.maxScrollExtent,
      duration: const Duration(milliseconds: 200),
      curve: Curves.easeOut,
    );
  }

  //消息发送
  void messageSend(String message, String photo) {
    setState(() {
      imList.add(Container(
          margin: const EdgeInsets.only(bottom: 12),
          child: CnMessageItemView(photo, message, () {
            scrollList();
          })));
    });

    scrollList();
  }
  // 请求摄像头权限，如果没有权限就会设置 mute掉本地视频流

  getPermission() async {
    PermissionStatus statuses = await Permission.camera.status;
    if (statuses != PermissionStatus.granted) {
      _rtcEngine?.enableLocalVideo(false);
    } else {
      _rtcEngine?.enableLocalVideo(true);
    }
// 请求麦克风权限，如果没有权限就会设置 mute掉本地视频流
// 请求麦克风权限，如果没有权限就会设置 mute掉本地视频流
    PermissionStatus statuses2 = await Permission.microphone.status;
    if (statuses2 != PermissionStatus.granted) {
      _rtcEngine?.enableLocalAudio(false);
    } else {
      _rtcEngine?.enableLocalAudio(true);
    }
  }

  void getCoins() {
    CnNetHelper.getUserCoins().then((value) {
      setState(() {
        availableCoins = value;
      });
    });
  }

  //关注
  void follow(BuildContext context) {
    CnAnchorViewModel.getInfo().follow(widget.userId, isFollow, (bool value) {
      if (value) {
        if (isFollow) {
          ToastUtils.show('unfollow success');
        } else {
          ToastUtils.show('follow success');
        }
        setState(() {
          isFollow = !isFollow;
        });
      } else {
        if (isFollow) {
          ToastUtils.show('unfollow failure');
        } else {
          ToastUtils.show('follow failure');
        }
      }
    });
  }

  @override
  Widget build(BuildContext context) {
    return WillPopScope(
        child: Scaffold(
            body: GestureDetector(
                onTap: () {
                  if (mounted) {
                    setState(() {
                      // 隐藏软键盘
                      FocusScope.of(context).unfocus();
                    });
                  }
                },
                child: Stack(
                  fit: StackFit.expand,
                  children: [
                    uid == 1
                        ? Container(
                            color: Colors.black,
                          )
                        : InkWell(
                            onTap: () {},
                            child: RtcRemoteView.SurfaceView(
                                uid: uid,
                                channelId: widget._CnChannelModel.channelName)),
                    CnMineVideoView(
                      widget._CnChannelModel,
                      uid,
                      openCamera: () {
                        if (isRear) {
                          isRear = false;
                          _rtcEngine?.setCameraCapturerConfiguration(
                              CameraCapturerConfiguration(
                                  cameraDirection: CameraDirection.Front));
                        } else {
                          isRear = true;
                          _rtcEngine?.setCameraCapturerConfiguration(
                              CameraCapturerConfiguration(
                                  cameraDirection: CameraDirection.Rear));
                        }
                      },
                    ),

                    Positioned(
                        top: 70,
                        right: 18,
                        child: InkWell(
                            onTap: () {
                              showDialog(
                                  context: context,
                                  builder: (BuildContext context) {
                                    return Dialog(
                                        child: Container(
                                            width: double.infinity,
                                            padding: const EdgeInsets.symmetric(
                                                vertical: 18),
                                            margin: const EdgeInsets.symmetric(
                                                horizontal: 18),
                                            decoration: BoxDecoration(
                                                color: Colors.white,
                                                borderRadius:
                                                    BorderRadius.circular(10)),
                                            child: Column(
                                              mainAxisSize: MainAxisSize.min,
                                              crossAxisAlignment:
                                                  CrossAxisAlignment.center,
                                              children: [
                                                Text('Are you sure to hangUp ?',
                                                    style: const TextStyle(
                                                        color: Colors.black,
                                                        fontSize: 18)),
                                                const SizedBox(height: 16),
                                                Row(children: [
                                                  InkWell(
                                                      onTap: () {
                                                        if (mounted) {
                                                          final routeToRemove =
                                                              ModalRoute.of(
                                                                  context);
                                                          Navigator.of(context)
                                                              .removeRoute(
                                                                  routeToRemove!);
                                                        }
                                                      },
                                                      child: Container(
                                                        decoration: BoxDecoration(
                                                            color: const Color(
                                                                0xffF2F2F2),
                                                            borderRadius:
                                                                BorderRadius
                                                                    .circular(
                                                                        18)),
                                                        padding:
                                                            const EdgeInsets
                                                                    .symmetric(
                                                                vertical: 4,
                                                                horizontal: 30),
                                                        child: Text(
                                                          'cancel',
                                                          style: const TextStyle(
                                                              color: Color(
                                                                  0xffBEBABA),
                                                              fontSize: 18),
                                                        ),
                                                      )),
                                                  const SizedBox(width: 18),
                                                  InkWell(
                                                      onTap: () {
                                                        if (mounted) {
                                                          final routeToRemove =
                                                              ModalRoute.of(
                                                                  context);
                                                          Navigator.of(context)
                                                              .removeRoute(
                                                                  routeToRemove!);
                                                        }
                                                        _hangUp();
                                                      },
                                                      child: Container(
                                                        decoration:
                                                            BoxDecoration(
                                                                borderRadius:
                                                                    BorderRadius
                                                                        .circular(
                                                                            18),
                                                                border:
                                                                    Border.all(
                                                                  color: Color(
                                                                      0xFFE71988),
                                                                  width:
                                                                      1.0, // 设置边框宽度
                                                                )),
                                                        padding:
                                                            const EdgeInsets
                                                                    .symmetric(
                                                                vertical: 4,
                                                                horizontal: 30),
                                                        child: Text(
                                                          'confirm',
                                                          style: const TextStyle(
                                                              color: Color(
                                                                  0xFFE71988),
                                                              fontSize: 18),
                                                        ),
                                                      ))
                                                ])
                                              ],
                                            )));
                                  });
                            },
                            child: Image.asset("images/ic_close_white.png",
                                width: 30, height: 30))),
                    //个人信息UI
                    Positioned(
                        left: 20, top: 65, child: getUserInfoWight(context)),
                    Positioned(
                        left: 18,
                        bottom: 90,
                        child: AnimatedOpacity(
                            duration: const Duration(milliseconds: 500),
                            opacity: 1.0, // 控制透明度以显示/隐藏
                            child: SizedBox(
                                width: 250,
                                height: 200,
                                child: ListView.builder(
                                    controller: _scrollController,
                                    itemCount: imList.length,
                                    itemBuilder:
                                        (BuildContext context, int index) {
                                      return imList[index];
                                    })))),

                    giftName == ""
                        ? const SizedBox()
                        : CnGiftAnimationView(giftName,
                            controller: _controller,
                            scaleController: _scaleController),
                    Positioned(
                        bottom: 100,
                        right: 33,
                        child: InkWell(
                            onTap: () {
                              _showGiftDialog(context, availableCoins, (index) {
                                if (index == 0) {
                                  Future.delayed(Duration(seconds: 1), () {
                                    CnAppPopPageView.showCustomModalBottomSheet(
                                        context,
                                        CnCoinStorePage(
                                          isPodPage: true,
                                        ));
                                  });
                                } else {
                                  if (availableCoins < 39) {
                                    ToastUtils.show('Not enough user coins.');
                                  } else {
                                    setState(() {
                                      giftName =
                                          "images/icon_gift_pc${index}.png";
                                    });
                                    _startGiftTimer();
                                    _startAnimation();
                                    //扣除金币接口
                                    CnNetHelper.reviewModeConsumeData(12,
                                        (HDHResponseData configData,
                                            bool result, String msg) async {
                                      if (result) {
                                        getCoins();
                                      }
                                    });
                                  }
                                }
                              });
                            },
                            child: Image.asset(
                                height: 41, width: 41, "images/ic_gift.png"))),

                    Positioned(
                        bottom: 20,
                        left: 18,
                        right: 18,
                        child:
                            Column(mainAxisSize: MainAxisSize.min, children: [
                          BottomKeyBoard(
                              expressionOnClick: () {
                                if (mounted) {
                                  setState(() {
                                    // 隐藏软键盘
                                    FocusScope.of(context).unfocus();
                                  });
                                }
                              },
                              inPutListen: (hasFocus) {
                                if (hasFocus) {}
                              },
                              messageSend: (String message) {
                                messageSend(
                                    message,
                                    Provider.of<ChangeUserInfoModel>(context,
                                                listen: false)
                                            .info
                                            .avatarUrl ??
                                        "");
                              },
                              controller: _editingController),
                        ])),
                  ],
                ))),
        onWillPop: () async {
          return false;
        });
  }

  //个人信息组件
  Container getUserInfoWight(BuildContext context) {
    return Container(
        height: 50,
        padding: EdgeInsets.only(left: 10, right: 10, top: 3, bottom: 3),
        decoration: const BoxDecoration(
            image: DecorationImage(
                fit: BoxFit.fill,
                image: AssetImage('images/icon_mate_btn_bg_coin.png'))),
        child: Row(children: [
          // const SizedBox(width: 7),
          Container(
            child: Row(
              children: [
                ClipRRect(
                    borderRadius: BorderRadius.circular(60), // 设置圆角半径
                    child: Image.network(_userInfo?.avatarUrl ?? "",
                        width: 40, height: 40, loadingBuilder: (
                      BuildContext context,
                      Widget child,
                      ImageChunkEvent? loadingProgress,
                    ) {
                      if (loadingProgress == null) {
                        return child;
                      } else {
                        return Image.asset(
                          'images/ic_placeholder.webp',
                          width: 31,
                          height: 31,
                        );
                      }
                    }, errorBuilder: (BuildContext context, Object error,
                            StackTrace? stackTrace) {
                      return Image.asset(
                        'images/ic_placeholder.webp',
                        width: 31,
                        height: 31,
                      );
                    })),
                const SizedBox(width: 7),
                Column(crossAxisAlignment: CrossAxisAlignment.start, children: [
                  const SizedBox(height: 3),
                  Text(getSubString(end: 5, str: _userInfo?.nickname ?? "LuCy"),
                      style: const TextStyle(
                          color: Colors.white,
                          fontSize: 17,
                          fontWeight: FontWeight.bold)),
                  const SizedBox(height: 3),
                  Row(children: [
                    Container(
                      child: Text((_userInfo?.age ?? 18).toString(),
                          style: const TextStyle(
                              fontSize: 12, color: Colors.black)),
                    ),
                    const SizedBox(width: 2),
                    Container(
                      child: Text(
                          getSubString(
                              end: 6, str: _userInfo?.country ?? "USA"),
                          style: const TextStyle(
                              fontSize: 12, color: Colors.black)),
                    )
                  ])
                ]),
                const SizedBox(width: 7),
                InkWell(
                    onTap: () {
                      //更多弹窗
                      CnAnchorViewModel.getInfo()
                          .showMoreDialog(context, _userInfo, () {
                        CnEventBus.instance!
                            .commit(EventKeys.HomeListPageMessage, null);
                        //关注、取消关注
                      });
                    },
                    child: Image.asset("images/icon_warning.png",
                        height: 30, width: 30))
              ],
            ),
          ),
          const SizedBox(width: 7),
          Container(
            child: InkWell(
                onTap: () {
                  follow(context);
                },
                child: !isFollow
                    ? Image.asset("images/ic_like_false.png",
                        height: 30, width: 30)
                    : Image.asset("images/ic_like_true.png",
                        height: 30, width: 30)),
          )
        ]));
  }
}

typedef FunctionTest<String> = void Function(int index);

//规则弹窗
void _showGiftDialog(context, availableCoins, FunctionTest<int> backBlock) {
  showDialog(
    context: context,
    builder: (BuildContext context) {
      return AlertDialog(
        contentPadding: const EdgeInsets.all(0),
        content: Container(
          decoration: const BoxDecoration(
              image: DecorationImage(
                  fit: BoxFit.fill,
                  image: AssetImage('images/icon_gift_bg.png'))),
          child: Column(
            mainAxisSize: MainAxisSize.min,
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              Container(
                // width: double.infinity,
                height: 44,
                child: Container(
                  margin: EdgeInsets.only(left: 16),
                  width: 76,
                  height: 30,
                  decoration: BoxDecoration(
                      image: DecorationImage(
                    image: AssetImage('images/icon_mate_btn_bg_coin.png'),
                  )),
                  child: Row(
                    mainAxisAlignment: MainAxisAlignment.center,
                    children: [
                      Container(
                        width: 19,
                        height: 17,
                        margin: EdgeInsets.only(left: 0),
                        child: Image.asset('images/icon_coins_logo_mine.png'),
                      ),
                      Container(
                        margin: EdgeInsets.only(left: 5),
                        child: Text(
                          '$availableCoins',
                          style:
                              TextStyle(fontSize: 13, color: Color(0xFF404040)),
                        ),
                      )
                    ],
                  ),
                ),
              ),
              SizedBox(
                height: 40,
              ),
              Row(
                mainAxisAlignment: MainAxisAlignment.spaceAround,
                children: [
                  InkWell(
                    onTap: () {
                      backBlock(1);
                      Navigator.of(context).pop();
                    },
                    child: Column(
                      children: [
                        Container(
                          width: 48,
                          height: 39,
                          child: Image.asset('images/icon_gift_pc1.png'),
                        ),
                        const SizedBox(height: 6),
                        Row(
                          mainAxisAlignment: MainAxisAlignment.center,
                          children: [
                            Container(
                              width: 19,
                              height: 17,
                              margin: EdgeInsets.only(left: 0),
                              child: Image.asset(
                                  'images/icon_coins_logo_mine.png'),
                            ),
                            Container(
                              margin: EdgeInsets.only(left: 5),
                              child: Text(
                                '39',
                                style: TextStyle(
                                    fontSize: 13, color: Color(0xFF404040)),
                              ),
                            )
                          ],
                        ),
                      ],
                    ),
                  ),
                  InkWell(
                    onTap: () {
                      backBlock(2);
                      Navigator.of(context).pop();
                    },
                    child: Column(
                      children: [
                        Container(
                          width: 48,
                          height: 39,
                          child: Image.asset('images/icon_gift_pc2.png'),
                        ),
                        const SizedBox(height: 6),
                        Row(
                          mainAxisAlignment: MainAxisAlignment.center,
                          children: [
                            Container(
                              width: 19,
                              height: 17,
                              margin: EdgeInsets.only(left: 0),
                              child: Image.asset(
                                  'images/icon_coins_logo_mine.png'),
                            ),
                            Container(
                              margin: EdgeInsets.only(left: 5),
                              child: Text(
                                '39',
                                style: TextStyle(
                                    fontSize: 13, color: Color(0xFF404040)),
                              ),
                            )
                          ],
                        ),
                      ],
                    ),
                  ),
                  InkWell(
                    onTap: () {
                      backBlock(3);
                      Navigator.of(context).pop();
                    },
                    child: Column(
                      children: [
                        Container(
                          width: 48,
                          height: 39,
                          child: Image.asset('images/icon_gift_pc3.png'),
                        ),
                        Row(
                          mainAxisAlignment: MainAxisAlignment.center,
                          children: [
                            Container(
                              width: 19,
                              height: 17,
                              margin: EdgeInsets.only(left: 0),
                              child: Image.asset(
                                  'images/icon_coins_logo_mine.png'),
                            ),
                            Container(
                              margin: EdgeInsets.only(left: 5),
                              child: Text(
                                '39',
                                style: TextStyle(
                                    fontSize: 13, color: Color(0xFF404040)),
                              ),
                            )
                          ],
                        ),
                      ],
                    ),
                  ),
                  InkWell(
                    onTap: () {
                      backBlock(4);
                      Navigator.of(context).pop();
                    },
                    child: Column(
                      children: [
                        Container(
                          width: 48,
                          height: 39,
                          child: Image.asset('images/icon_gift_pc4.png'),
                        ),
                        const SizedBox(height: 6),
                        Row(
                          mainAxisAlignment: MainAxisAlignment.center,
                          children: [
                            Container(
                              width: 19,
                              height: 17,
                              margin: EdgeInsets.only(left: 0),
                              child: Image.asset(
                                  'images/icon_coins_logo_mine.png'),
                            ),
                            Container(
                              margin: EdgeInsets.only(left: 5),
                              child: Text(
                                '39',
                                style: TextStyle(
                                    fontSize: 13, color: Color(0xFF404040)),
                              ),
                            )
                          ],
                        ),
                      ],
                    ),
                  )
                ],
              ),
              const SizedBox(height: 52),
              Row(
                mainAxisAlignment: MainAxisAlignment.end,
                children: [
                  InkWell(
                    onTap: () {
                      backBlock(0);
                      Navigator.of(context).pop();
                    },
                    child: Container(
                        margin: EdgeInsets.only(right: 16),
                        // width: 252,
                        height: 40,
                        alignment: Alignment.center,
                        decoration: const BoxDecoration(
                            image: DecorationImage(
                                image: AssetImage(
                                    'images/icon_coin_bg_mine.png'))),
                        child: Container(
                          padding: EdgeInsets.all(10),
                          child: Text(
                            'Coin Store',
                            style: TextStyle(
                                fontSize: 18, color: Color(0xFFE71988)),
                          ),
                        )),
                  ),
                ],
              ),
              const SizedBox(height: 12),
            ],
          ),
        ),
      );
    },
  );
}
